package com.central.apps.handler;

import com.central.app.service.AppCommonService;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.common.util.ToolUtil;
import com.central.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class DemandApplyHandler extends LvBaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Autowired
    private AppCommonService appCommonService;

    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if("demandapplyApp".equals(app) && "bl_demandapply".equals(objName)){
            String demandnum = MapUtils.getString(data,"demandnum");
            String purchasenum = MapUtils.getString(data,"purchasenum");
            String oldPurchasenum = "";
            if(isUpdate){
                //更新
                Long id = MapUtils.getLong(data,"id");
                Map<String,Object> olddata = handlerService.findById(app,objName,id);
                oldPurchasenum = MapUtils.getString(olddata,"purchasenum");
            }
            if(ToolUtil.isNotEmpty(purchasenum) && !purchasenum.equals(oldPurchasenum)){
                //只要不相等，就清空重新插入
                String delSql = "delete from bl_demandapplyline where demandnum='"+demandnum+"'";
                handlerService.updateBySql(delSql);
                //重新插入
                String insertSql = "select '' as id,itemnum,itemdesc,unit,quantity,model,'"+demandnum+"' as demandnum,'物资' as linetype from bl_purchaseplanline where purchasenum='"+purchasenum+"'";
                List<Map<String,Object>> newPurLineList = handlerService.findBySql(insertSql);
                handlerService.batchInsert(app,"bl_demandapplyline",newPurLineList);
            }
        }

    }

}
